package id3.controllers;

import id3.models.Attribute;
import id3.models.RowData;
import id3.models.TreeNode;
import id3.utils.Constants;
import id3.utils.LoadFile;
import id3.utils.Utils;
import java.util.ArrayList;

public class ID3Alg {

    static Attribute[] attributes = Constants.getMapAttrs();

    public static TreeNode ID3_Alg(ArrayList<RowData> dataProcessed, String[] classLabel, ArrayList<Integer> attrIndexs) {

        ArrayList<RowData> training;
        ArrayList<RowData> training1;
        training1 = Utils.cloneData(dataProcessed);

        TreeNode root;

        String label = checkOneClass(training1);
        if (label != null) {
            return new TreeNode(new Attribute(label));
        }

        if (attrIndexs.size() == 0) {
            String mostLabel = mostLabel(training1, classLabel);
            return new TreeNode(new Attribute(mostLabel));
        }

        int indexAttr = chooseAttribute(training1, attrIndexs);
        training = ContinuousToDiscrete.missValue(training1, indexAttr);
        Attribute attr = attributes[indexAttr];
        root = new TreeNode(attr);

        for (String value : attr.getStringValues()) {
            root.addValues(value);
            TreeNode child;
            ArrayList<RowData> subTraining = getSubTraining(training, indexAttr, value);
            if (subTraining.size() == 0) {
                String mostLabel = mostLabel(training, classLabel);
                child = new TreeNode(new Attribute(mostLabel));
                root.addChilds(child);
            } else {
                
                ArrayList<Integer> subAttrIndexs = new ArrayList<>();
                for (Integer a : attrIndexs) {
                    subAttrIndexs.add(a);
                }
                subAttrIndexs.remove((Object)indexAttr);
                child = ID3_Alg(subTraining, classLabel, subAttrIndexs);
                root.addChilds(child);
                
//                for (int i = 0; i < attrIndexs.size(); i++) {
//                    if (attrIndexs.get(i) == indexAttr) {
//                        attrIndexs.remove(i);
//                        break;
//                    }
//                }
////                subAttrIndexs.remove((Object)indexAttr);
//                child = ID3_Alg(subTraining, classLabel, attrIndexs);
//                root.addChilds(child);
            }
        }

        return root;

    }

    //ham tra lai thu tu thuoc tinh can kiem tra
    public static int chooseAttribute(ArrayList<RowData> dataProcessed, ArrayList<Integer> attrIndexs) {

        int index = attrIndexs.get(0);
        float gainMax = InformationGain.calInfoGain(dataProcessed, attrIndexs.get(0));
        for (int i = 1; i < attrIndexs.size(); i++) {
            float gainI = InformationGain.calInfoGain(dataProcessed, attrIndexs.get(i));
            if (gainMax > gainI) {
                gainMax = gainI;
                index = attrIndexs.get(i);
            }
        }

        return index;
    }

    /**
     * kiem tra tap training co thuoc cung mot lop ko neu thuoc mot lop thi tra
     * ve lop do neu ko thi tra ve null
     *
     * @param training
     * @return
     */
    public static String checkOneClass(ArrayList<RowData> training) {
//        ContinuousToDiscrete.print(training);
        String label = training.get(0).getRow().get(Constants.NUMBER_ATTRIBUTE - 1);
        for (RowData row : training) {
            if (!row.getRow().get(Constants.NUMBER_ATTRIBUTE - 1).equals(label)) {
                return null;
            }
        }
        return label;
    }

    private static String mostLabel(ArrayList<RowData> training, String[] classLabel) {
        int max = 0;
        String labelMax = null;
        int count;

        for (String label : classLabel) {
            count = 0;
            for (RowData row : training) {
                if (row.getRow().get(Constants.NUMBER_ATTRIBUTE - 1).equals(label)) {
                    count++;
                }
            }
            if (max < count) {
                max = count;
                labelMax = label;
            }
        }
        return labelMax;
    }

    public static ArrayList<RowData> getSubTraining(ArrayList<RowData> training_data, int indexAttr, String value) {
//        ContinuousToDiscrete.print(training_data);
        //System.out.println("value: " +  value +  " index: " + indexAttr);
        ArrayList<RowData> training = new ArrayList<>();
        training = Utils.cloneData(training_data);
        ArrayList<RowData> subTraining = new ArrayList<>();
        for (RowData row : training) {
            if (row.getRow().get(indexAttr).equals(value)) {
                subTraining.add(row);
            }

        }
        return subTraining;
    }

    public static String queryTree(RowData row, TreeNode root) {

        TreeNode node = root;
        while (node != null) {
            boolean a = false;
            if (node.getAttrNode().getLabel() != null) {
                return node.getAttrNode().getLabel();
            }
//            System.out.println("root: " + node.getAttrNode().getName());
            for (int i = 0; i < Constants.getMapAttrs().length - 1; i++) {
                //lay vi tri thuoc tinh cua node trong row
                if (Constants.getMapAttrs()[i].getName().equals(node.getAttrNode().getName())) {
                    for (int j = 0; j < node.getmValues().size(); j++) {
//                        System.out.println(node.getmValues().get(j) + "BBB: " + row.getRow().get(i));
                        if (node.getmValues().get(j).equals(row.getRow().get(i))) {
                            node = node.getmChilds().get(j);
                            a = true;
                            break;
                        } else {
//                            node = null;
//                            System.out.println("node null");
                        }
                    }
                    break;
                } else {
//                    node = null;
//                    System.out.println("AAAAAAAAAAAAAAA");
                }
            }
            if (!a) {
                node = null;
            }
        }
        return null;

    }

    public static String test(String fileTest, TreeNode root) {
        StringBuilder result = new StringBuilder();
        try {
            ArrayList<RowData> testData = LoadFile.getData(fileTest);
            int[] arrCont = ContinuousToDiscrete.arrIndexAttrCont;
            for (RowData row : testData) {
                for (int i = 0; i < arrCont.length; i++) {
                    if (ContinuousToDiscrete.getContValue(row.getRow().get(arrCont[i])) > ContinuousToDiscrete.getPosition()[i]) {
                        row.getRow().set(arrCont[i], Constants.HIGHT);
                    } else {
                        row.getRow().set(arrCont[i], Constants.LOW);
                    }
                }
            }
            result.append("\n  - Số lượng ví dụ : ").append(testData.size());
            int correct = 0, inCorrect = 0;
            if (testData != null) {
                for (RowData testData1 : testData) {
                    String label = queryTree(testData1, root);
                    if (label != null && label.compareToIgnoreCase(testData1.getRow().get(15)) != 0) {
                        inCorrect++;
                    } else{
                        correct++;
                    }
                }
            }
            result.append("\n  - Số kết quả đúng : ").append(correct);
            result.append("\n  - Số kết quả sai : ").append(inCorrect);
            result.append("\n  - Độ chính xác  : ").append(correct*100/(float)(correct+inCorrect)).append(" %");

        } catch (Exception ex) {
        }
        return result.toString();
    }

}
